package org.ssp.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.bouncycastle.util.IPAddress;
import org.ssp.service.CoreService;
import org.ssp.service.WXPayService;
import org.ssp.util.CommonUtil;
import org.ssp.util.XML2Obj2XML;

import net.sf.json.JSONObject;

/**
 * 微信支付相关的处理
 * 
 */
@WebServlet("/pay")
public class WXPayServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger=Logger.getLogger(CoreServlet.class);


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String method=request.getParameter("method");
		if("jsapi".equals(method)){
			System.out.println("pay..method.jsapi..");
			String openid=request.getParameter("openid");
			String goods=request.getParameter("goods");
			String price=request.getParameter("price");
			System.out.println("openid:"+openid);
			System.out.println("goods:"+goods);
			System.out.println("price:"+price);
	        
			SortedMap<Object,Object> paramaters=new TreeMap<Object,Object>();
			paramaters.put("appid",CoreService.AppID);
			paramaters.put("mch_id", WXPayService.MCH_ID);
			paramaters.put("nonce_str", WXPayService.CreateNoncestr());
			paramaters.put("body",goods);
			paramaters.put("out_trade_no", WXPayService.CreatePno());//商户订单号
			paramaters.put("total_fee", price);//"1"
			paramaters.put("spbill_create_ip",InetAddress.getLocalHost().getHostAddress().toString());
			paramaters.put("notify_url", WXPayService.NOTIFY_URL);
			paramaters.put("trade_type", "JSAPI");
			paramaters.put("openid", openid);
			paramaters.put("attach", goods);
			String sign=WXPayService.createSign("utf-8", paramaters);
			System.out.println("sign:"+sign);
			paramaters.put("sign", sign);
			System.out.println("in......");
			String requestxml=XML2Obj2XML.Obj2XML(paramaters);
			System.out.println("requestxml"+requestxml);
			System.out.println("out....");
			String result=WXPayService.getOrderMap(requestxml);
			System.out.println("result..."+result);
			//json-lib解析xml->obj
			Map<String, String> map=null;
			try {
				map = XML2Obj2XML.doXMLParse(result);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String return_code=map.get("return_code");
			String return_msg=map.get("return_msg");
			System.out.println("return-code...."+return_code);
			System.out.println("return_msg...."+return_msg);
		
			SortedMap<Object,Object> params = new TreeMap<Object,Object>();			JSONObject json=new JSONObject();
			params.put("appId", map.get("appid"));
			params.put("timeStamp",  WXPayService.getUnixTime(new Date()));
			String str= WXPayService.CreateNoncestr();
			params.put("nonceStr",str);
			params.put("package","prepay_id="+map.get("prepay_id"));
			params.put("signType", "MD5");
			

			//按照jsapi参数生成一个sign供前端使用
			String paySign=WXPayService.createSign("utf-8", params);
			System.out.println("appId:"+ map.get("appid"));
			System.out.println("timeStamp:"+WXPayService.getUnixTime(new Date()));
			System.out.println("package:"+"prepay_id="+map.get("prepay_id"));
			System.out.println("signType:MD5");
			System.out.println("nonceStr:"+str);
			System.out.println("paySign:"+paySign);
			
			params.put("paySign", paySign);
	        params.put("packageValue", "prepay_id="+map.get("prepay_id"));    //这里用packageValue是预防package是关键字在js获取值出错
			params.put("sendUrl", CoreService.BaseUrl+"/user/userupgrade-2");
			JSONObject resultjson=new JSONObject();
			resultjson.element("ordermap", params);
			PrintWriter out=response.getWriter();
			out.write(resultjson.toString());
			System.out.println(resultjson.toString());
			return;
		}else if("jsapi2".equals(method)){
			System.out.println("pay..method.jsapi..");
			String openid=request.getParameter("openid");
			String goods=request.getParameter("goods");
			String price=request.getParameter("price");
			Integer id=Integer.valueOf(request.getParameter("id"));
			
			System.out.println("openid:"+openid);
			System.out.println("goods:"+goods);
			System.out.println("price:"+price);
			System.out.println("id"+id);
	        
			SortedMap<Object,Object> paramaters=new TreeMap<Object,Object>();
			paramaters.put("appid",CoreService.AppID);
			paramaters.put("mch_id", WXPayService.MCH_ID);
			paramaters.put("nonce_str", WXPayService.CreateNoncestr());
			paramaters.put("body",goods);
			paramaters.put("out_trade_no", WXPayService.CreatePno());//商户订单号
			paramaters.put("total_fee", price);//"1"
			paramaters.put("spbill_create_ip",InetAddress.getLocalHost().getHostAddress().toString());
			paramaters.put("notify_url", WXPayService.NOTIFY_URL);
			paramaters.put("trade_type", "JSAPI");
			paramaters.put("openid", openid);
			paramaters.put("attach", String.valueOf(id));
			String sign=WXPayService.createSign("utf-8", paramaters);
			System.out.println("sign:"+sign);
			paramaters.put("sign", sign);
			System.out.println("in......");
			String requestxml=XML2Obj2XML.Obj2XML(paramaters);
			System.out.println("requestxml"+requestxml);
			System.out.println("out....");
			String result=WXPayService.getOrderMap(requestxml);
			System.out.println("result..."+result);
			//json-lib解析xml->obj
			Map<String, String> map=null;
			try {
				map = XML2Obj2XML.doXMLParse(result);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String return_code=map.get("return_code");
			String return_msg=map.get("return_msg");
			System.out.println("return-code...."+return_code);
			System.out.println("return_msg...."+return_msg);
		
			SortedMap<Object,Object> params = new TreeMap<Object,Object>();			JSONObject json=new JSONObject();
			params.put("appId", map.get("appid"));
			params.put("timeStamp",  WXPayService.getUnixTime(new Date()));
			String str= WXPayService.CreateNoncestr();
			params.put("nonceStr",str);
			params.put("package","prepay_id="+map.get("prepay_id"));
			params.put("signType", "MD5");
			

			//按照jsapi参数生成一个sign供前端使用
			String paySign=WXPayService.createSign("utf-8", params);
			System.out.println("appId:"+ map.get("appid"));
			System.out.println("timeStamp:"+WXPayService.getUnixTime(new Date()));
			System.out.println("package:"+"prepay_id="+map.get("prepay_id"));
			System.out.println("signType:MD5");
			System.out.println("nonceStr:"+str);
			System.out.println("paySign:"+paySign);
			
			params.put("paySign", paySign);
	        params.put("packageValue", "prepay_id="+map.get("prepay_id"));    //这里用packageValue是预防package是关键字在js获取值出错
			params.put("sendUrl", CoreService.BaseUrl+"/user/userupgrade-2");
			JSONObject resultjson=new JSONObject();
			resultjson.element("ordermap", params);
			PrintWriter out=response.getWriter();
			out.write(resultjson.toString());
			System.out.println(resultjson.toString());
			return;
		}
	}
}
